<!--
 单图展示零件
 提供更好的加载体验
 应仅针对于远程服务器中的图片，内联图片不应使用该组件加载。
 注意：
 1. overflow熟悉可能会影响3d动画效果，导致3d动画变2d;
 2. 使用时需要定义尺寸，当前组件不能自适应。
-->
<template>
  <div :class="css.default">
    <div :class="[css.body, {[css.flip]: flip, [css.loaded]: loaded}]" :style="perspectiveStyle">
      <div :class="[css.placeholder, css.front]" class="front">
        <slot name="placeholder">
          <img :src="placeholder" :class="css.image"/>
        </slot>
      </div>
      <div :class="[css.wrap, css.back, {[css.clip]: !skew}]" class="back">
        <img :src="src"  @load="onLoad" :class="skew ? css.LichKing : css.Arthas">
        <slot :class="css.slot"/>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'r-image',
  props: {
    src: String,
    // 是否启用3d翻转效果
    flip: Boolean,
    // 平铺策略
    // skew: true， 水平垂直方向兼平铺，即扭曲优先。
    // skew: false, 图片不扭曲，水平方向平铺，垂直方向自动溢出，底部溢出时被裁剪。
    skew: Boolean
  },
  data () {
    return {
      loaded: false,
      placeholder: require('../images/placeholder.png'),
      // 透视距离，单位px
      perspective: null
    }
  },
  computed: {
    perspectiveStyle () {
      const {flip, perspective} = this
      return (flip && perspective) ? {
        '-webkit-perspective': `${perspective.toFixed()}px`,
        perspective: `${perspective.toFixed()}px`
      } : null
    }
  },
  mounted () {
    const {flip} = this
    if (!flip) return
    const width = this.$el.clientWidth
    const height = this.$el.clientHeight
    this.perspective = Math.sqrt(width * width + height * height) * 1.8
  },
  methods: {
    onLoad (event) {
      const Terenas = event.target.parentNode
      const Menethil = Terenas.parentNode
      Terenas.style.height = Menethil.clientHeight + 'px'
      this.loaded = true
      this.$emit('load', event)
    }
  }
}
</script>
<style module="css" lang="scss">
  @import "../styles/index";

  .default {
    min-width: 40px;
    min-height: 40px;
  }

  .body {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .front,
  .back {
    backface-visibility: hidden;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 0;
  }

  .front {
    width: 100%;
    height: 100%;
    opacity: 0.9;
  }

  .image {
    max-height: 60%;
    max-width: 60%;
    margin: auto;
  }

  .back {
    transform: rotateY(180deg);
  }

  .flip {
    .front,
    .back {
      transition: transform 1.2s ease-in-out;
      transform-style: preserve-3d;
    }
  }

  .loaded {
    .front {
      transform: rotateY(-180deg);
    }

    .back {
      transform: rotateY(0deg);
    }
  }

  .placeholder {
    color: #ccc;
    background-color: white;
    @extend %flex-center;

    svg {
      width: 60%;
      fill: currentColor;
    }
  }

  .wrap {
    width: 100%;
  }

  .clip {
    overflow: hidden;
  }

  .Arthas,
  .LichKing {
    display: block;
    width: 100%;
  }

  .Arthas {
    height: auto;
  }

  .LichKing {
    height: 100%;
  }
</style>
